﻿'Copyright (c) 2009 Grailtek

'Permission is hereby granted, free of charge, to any person
'obtaining a copy of this software and associated documentation
'files (the "Software"), to deal in the Software without
'restriction, including without limitation the rights to use,
'copy, modify, merge, publish, distribute, sublicense, and/or sell
'copies of the Software, and to permit persons to whom the
'Software is furnished to do so, subject to the following
'conditions:

'The above copyright notice and this permission notice shall be
'included in all copies or substantial portions of the Software.

'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'OTHER DEALINGS IN THE SOFTWARE.

Imports System.Reflection
Imports System.Data.SqlClient
Imports System.DataExecutorServices.Exceptions
Imports Microsoft.SqlServer.Management.Smo

Public NotInheritable Class DataTypeConverter

    Private Sub New()
    End Sub

    Public Shared Function GetDataTypeFor(ByVal t As Type) As DataType
        Dim ret As DataType = Nothing
        Dim dbtype As DbType = GetDbTypeFor(t)
        SmoDataTypeDbTypeLookup.TryGetValue(dbtype, ret)
        If ret Is Nothing Then Throw New DbTypeMappingException(t, Nothing)
        Return ret
    End Function

    Private Shared SmoDataTypeDbTypeLookup As Dictionary(Of DbType, DataType) = GetSmoDataTypeDbTypeLookup()
    'TODO: this should be good enough for now but I may want an expert to eyeball this mapping later
    'this is meant to serve as a default paramater type provider, so lengths are unimportant
    Private Shared Function GetSmoDataTypeDbTypeLookup() As Dictionary(Of DbType, DataType)
        Dim dic As New Dictionary(Of DbType, DataType)
        dic.Add(Data.DbType.AnsiString, DataType.NVarChar(20))
        dic.Add(Data.DbType.AnsiStringFixedLength, DataType.NChar(20))
        dic.Add(Data.DbType.Binary, DataType.Binary(20))
        dic.Add(Data.DbType.Boolean, DataType.Bit)
        dic.Add(Data.DbType.Byte, DataType.SmallInt)
        dic.Add(Data.DbType.Currency, DataType.Money)
        dic.Add(Data.DbType.Date, DataType.DateTime)
        dic.Add(Data.DbType.DateTime, DataType.DateTime)
        dic.Add(Data.DbType.DateTime2, DataType.DateTime)
        dic.Add(Data.DbType.DateTimeOffset, DataType.DateTime)
        dic.Add(Data.DbType.Decimal, DataType.Decimal(9, 18))
        dic.Add(Data.DbType.Double, DataType.Float)
        dic.Add(Data.DbType.Guid, DataType.UniqueIdentifier)
        dic.Add(Data.DbType.Int16, DataType.Int)
        dic.Add(Data.DbType.Int32, DataType.Int)
        dic.Add(Data.DbType.Int64, DataType.Int)
        dic.Add(Data.DbType.Object, DataType.Variant)
        dic.Add(Data.DbType.SByte, DataType.SmallInt)
        dic.Add(Data.DbType.Single, DataType.Float)
        dic.Add(Data.DbType.String, DataType.VarChar(20))
        dic.Add(Data.DbType.StringFixedLength, DataType.Char(10))
        dic.Add(Data.DbType.Time, DataType.DateTime)
        dic.Add(Data.DbType.UInt16, DataType.Int)
        dic.Add(Data.DbType.UInt32, DataType.Int)
        dic.Add(Data.DbType.UInt64, DataType.Int)
        dic.Add(Data.DbType.VarNumeric, DataType.Int)
        dic.Add(Data.DbType.Xml, DataType.Xml("unk"))
        Return dic
    End Function

    'a general type to sql parameter conversion maps from a large and undefined set of possibilities;
    'both the type set and the official mapping could change over time;
    'this method uses SqlParameter's built-in conversion, which requires that an instance be created since we can't get at the internal mapping
    'we want to use the built-in method anyway since it will always be there and updated
    '... even if I wanted to swipe the internal type conversion function, I can't use MetaType
    Public Shared Function GetDbTypeFor(ByVal t As Type) As DbType
        Dim ret As DbType = Nothing
        Static dic As New Dictionary(Of Type, DbType)
        If Not dic.TryGetValue(t, ret) Then
            Dim o As Object = Nothing
            'NOTE: string and GUID are the only types I know of that pass as valid SQL parameters and do not have parameterless c'tors
            If t Is GetType(String) Then
                o = ""
            ElseIf t Is GetType(Guid) Then
                o = Guid.NewGuid
            Else
                If t.IsArray Then
                    o = System.Array.CreateInstance(t.GetElementType, 0)
                Else
                    If HasPublicParameterlessConstructor(t) Then
                        o = Activator.CreateInstance(t)
                    Else
                        'I think if we get here Object is OK to use
                        o = New Object
                    End If
                End If
            End If
            Dim p As New SqlParameter With {.Value = o}
            Try
                ret = p.DbType
                SyncLock (dic)
                    If Not dic.ContainsKey(t) Then
                        'we add to the result to the dictionary inside this try catch block so an exception will always be raised for a bad data type
                        dic.Add(t, ret)
                    End If
                End SyncLock
            Catch ex As ArgumentException
                Throw New DbTypeMappingException(t, ex)
            End Try
        End If
        Return ret
    End Function

    Private Shared Function HasPublicParameterlessConstructor(ByVal type As Type) As Boolean
        If type.IsGenericType Then Return False
        If type.IsValueType Then Return True
        For Each ctorInfo As ConstructorInfo In type.GetConstructors()
            If ctorInfo.GetParameters.Count = 0 Then Return True
        Next
    End Function

End Class